// lib/pages/ArticleDetail/ArticleDetailPage.dart
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:html/dom.dart' as dom;
import 'package:metaera_flutter/utils/Device.dart';
import 'package:metaera_flutter/utils/Font.dart';
import 'package:metaera_flutter/widgets/ArticleContentView.dart';
import 'package:metaera_flutter/widgets/NavigationView.dart';
import '../../widgets/Toasts.dart';
import '../../utils/Color.dart';
import '../../net/request.dart';
import '../../models/ArticleModel.dart';

class ArticleDetailPage extends StatefulWidget {
  final int articleId;
  const ArticleDetailPage({super.key, required this.articleId});

  @override
  State<ArticleDetailPage> createState() => _ArticleDetailPageState();
}

class _ArticleDetailPageState extends State<ArticleDetailPage> {
  late ArticleModel articleModel;
  bool _isLoading = true;
  bool _hasError = false;
  bool _isFollowing = false; // 关注状态

  @override
  void initState() {
    super.initState();
    // 初始化一个空的 ArticleModel 实例
    articleModel = ArticleModel(id: 0);
    _loadNewsDetails();
  }

  @override
  void dispose() {
    // 清理资源（如果有的话）
    super.dispose();
  }

  void _shareNews() {
    Toasts.success('分享');
  }

  void _loadNewsDetails() async {
    try {
      final result = await Request().getInformationDetails({
        "id": widget.articleId,
      });

      // 检查组件是否仍然挂载
      if (!mounted) return;

      if (result['code'] != 200) {
        Toasts.error("获取资讯数据失败，请刷新");
        setState(() {
          _hasError = true;
          _isLoading = false;
        });
        return;
      } else {
        setState(() {
          articleModel = ArticleModel.fromJson(result['data']);
          _isLoading = false;
          _hasError = false;
        });
      }
    } catch (e) {
      // 检查组件是否仍然挂载
      if (!mounted) return;

      Toasts.error("获取资讯数据失败，请刷新");
      setState(() {
        _hasError = true;
        _isLoading = false;
      });
    }
  }

  // 关注/取消关注操作
  void _toggleFollow() {
    // 检查组件是否仍然挂载
    if (!mounted) return;

    setState(() {
      _isFollowing = !_isFollowing;
    });

    // 这里可以添加实际的关注/取消关注API调用
    if (_isFollowing) {
      Toasts.success('已关注');
    } else {
      Toasts.success('已取消关注');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: NavigationView(
        title: _isLoading ? '加载中...' : (articleModel.title ?? '无标题'),
        actions: [
          IconButton(
            icon: Image.asset(
              'assets/images/base/more.png',
              width: 20,
              height: 20,
            ),
            onPressed: _shareNews,
          ),
        ],
      ),
      body: _isLoading
          ? _buildLoadingView()
          : _hasError
          ? _buildErrorView()
          : _buildContentView(),
    );
  }

  Widget _buildLoadingView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(AppColors.color6184DD),
          ),
          SizedBox(height: 16),
          Text(
            '正在加载文章内容...',
            style: TextStyle(color: AppColors.color9C9C9C, fontSize: 14),
          ),
        ],
      ),
    );
  }

  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, size: 48, color: AppColors.color9C9C9C),
          SizedBox(height: 16),
          Text(
            '加载失败，请刷新重试',
            style: TextStyle(color: AppColors.color9C9C9C, fontSize: 16),
          ),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: _loadNewsDetails,
            child: Text('重新加载'),
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.color6184DD,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildContentView() {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 文章标题
          Padding(
            padding: EdgeInsets.only(
              left: DeviceUtils.width16,
              right: DeviceUtils.width16,
              top: DeviceUtils.width10,
              bottom: DeviceUtils.width20,
            ),
            child: Text(
              articleModel.title ?? '无标题',
              style: TextStyle(
                fontSize: AppFonts.fontSize18,
                fontWeight: AppFonts.fontWeight600,
                color: AppColors.color000,
              ),
            ),
          ),

          // 文章信息
          Padding(
            padding: EdgeInsets.only(
              left: DeviceUtils.width16,
              right: DeviceUtils.width16,
              bottom: DeviceUtils.width10,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Text(
                      articleModel.author?.nickname ?? '未知作者',
                      style: TextStyle(
                        fontSize: AppFonts.fontSize14,
                        color: AppColors.color333,
                        fontWeight: AppFonts.fontWeight600,
                      ),
                    ),
                    SizedBox(width: DeviceUtils.width8),
                    Text(
                      articleModel.releaseTime ?? '',
                      style: TextStyle(
                        fontSize: AppFonts.fontSize14,
                        color: AppColors.color9C9C9C,
                      ),
                    ),
                  ],
                ),
                // 关注按钮
                GestureDetector(
                  onTap: _toggleFollow,
                  child: Container(
                    alignment: Alignment.center,
                    width: DeviceUtils.adaptiveSizeByScreenUtil(60),
                    height: DeviceUtils.adaptiveSizeByScreenUtil(28),
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: _isFollowing
                            ? AppColors.color6184DD
                            : AppColors.color9C9C9C,
                      ),
                      color: _isFollowing
                          ? AppColors.color6184DD
                          : Colors.transparent,
                      borderRadius: BorderRadius.circular(DeviceUtils.width12),
                    ),
                    child: Text(
                      _isFollowing ? '已关注' : '关注',
                      style: TextStyle(
                        fontSize: AppFonts.fontSize12,
                        color: _isFollowing
                            ? Colors.white
                            : AppColors.color9C9C9C,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),

          SizedBox(height: DeviceUtils.width6),

          ArticleContentView(content: articleModel.content ?? ""),

          SizedBox(height: DeviceUtils.width24),
        ],
      ),
    );
  }
}
